import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Main from '../views/main/Main'
import Register from '../views/Register'
import AddRetailer from '../views/main/AddRetailer'
import AddGoods from "../views/main/AddGoods";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Login',
        component: Login,
        meta: {
            requireAuth: false,
            title: "登录"
        }
    },
    {
        path: '/main',
        name: 'Main',
        component: Main,
        meta: {requireAuth: true, title: "首页"}
    },
    {
        path: '/register',
        name: 'Register',
        component: Register,
        meta: {requireAuth: false,title: "注册"}
    },
    {
        path: '/addRetailer',
        name: 'AddRetailer',
        component: AddRetailer,
        meta: {requireAuth: true}
    },
    {
        path: '/addGoods',
        name: 'AddGoods',
        component: AddGoods,
        meta: {requireAuth: true}
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title
    }
    next()
    if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
        if (localStorage.getItem('token')) { //判断本地是否存在token
            next();
        } else {
            if (to.path === '/') {
                next();
            } else {
                next({
                    path: '/'
                })
            }
        }
    } else {
        next();
    }
})
export default router